<template>
  <div>
    <el-form
      class=""
      ref="form"
      :model="form"
      label-width="100px"
      style="width: 600px"
      :rules="rules"
    >
      <el-form-item label="景点名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入景点名称"></el-input>
      </el-form-item>
      <el-form-item label="景点照片" prop="picture">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:9000/upload"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
        >
          <img v-if="form.picture" :src="form.picture" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="景点介绍" prop="detail">
        <el-input
          type="textarea"
          v-model="form.detail"
          placeholder="请输入介绍"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">立即新增</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: '',
        detail: '',
        picture: '',
      },
      rules: {
        title: [
          { required: true, message: '请填入景点名称', trigger: 'blur' },
          { min: 1, max: 30, message: '字符长度[1-30]', trigger: 'blur' },
        ],
        detail: [
          { required: true, message: '请填入景点介绍', trigger: 'blur' },
          { min: 0, max: 300, message: '字符长度[0-300]', trigger: 'blur' },
        ],
        picture: [{ required: true, message: '必选择图片', trigger: 'blur' }],
      },
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.form.picture = res.data
    },
    submit() {
      console.log(this.form)
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 发送请求，添加新景点到数据库
          this.$http.spotApi.add(this.form).then(res => {
            console.log(res)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: '新增景点成功',
              })
              // 回到上一页
              this.$router.push('/home/spot-list')
            }
          })
        }
      })
    },
  },
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 200px;
  height: 200px;
  display: block;
}
</style>
